function Clock() {
    this.seconds=0;
    this.part=0;
    this.idInterval=null;
    this.finished=false;
    this.isRunning=function() {return (this.idInterval!=null);}
    this.start=function(){
        this.idInterval=self.setInterval("reloj.cycle()",1000);
    }
    this.stop=function(){
        clearInterval(this.idInterval);
        this.idInterval=null;
    }
    this.cycle=function(){
        if(this.finished){
            $(".time").html('<div><span id="label_finished">Finished</span></div>');
        }else{
            $("#label_time").html("min " + Math.floor((this.seconds++)/60));
            $("#label_part").html((this.part*1)+1);
        }
    }
}

function Event(eventid){
    this.eventId = eventid;
}

var reloj, evento;

function refresh() {
    $.ajax({
        type: "GET",
        url: "/api?method=refreshEvent",
        data: "tokenEvent="+evento.eventId+"&part="+reloj.part+"&time="+reloj.seconds+"&running="+reloj.isRunning(),
        dataType: "json",
        cache: false,
        success: function(data){
            if(data['tm']!=undefined && data['tm']['time']!=undefined){
                if(reloj.seconds+5<data['tm']['time'])
                    $(".time").addClass("running");
                else
                    $(".time").removeClass("running");
                reloj.seconds=data['tm']['time'];
                reloj.part=(data['tm']['part']-1);
                reloj.cycle();
            }
            var finished=data['finished'];
            if(finished){
                reloj.finished=true;
                reloj.cycle();
            }
            var end=data['end'];
            if (end && !finished)
                $(".btnEnd").show();
            else
                $(".btnEnd").hide();
            var start=data['start'];
            if (start && !finished)
                $(".btnStart").show();
            else
                $(".btnStart").hide();

            var pause=data['pause'];
            $(".btnStart").val(pause?"pause":"start");

            ps=data["ps"];
            for (p in ps){
                $("#score"+p).html(ps[p]['s']);
            }
            as=data["as"]
            actions = $(".actions");
            action = "";
            part=1;
            for (a in as){
                
                if(as[a]["an"]=="")
                    action="<div class='action'><p><b>Fin de la parte nº "+(part++)+"</b></p></div>"+action;
                else
                    action = "<div class='action'><p>min %min%: %action% de %participant%</p></div>"
                        .replace("%min%", Math.round(as[a]["t"]/60)).replace("%action%", as[a]["an"])
                        .replace("%participant%", as[a]["pn"])+action;
            }
            actions.html(action);
        }
    });
}

$(function(){

    reloj=new Clock();
    evento=new Event($("#eventid").val());
    reloj.seconds=$("#seconds").val();
    reloj.part=$("#part").val();
    if(reloj.part<0)
        reloj.part=0;
    $(".btn_action").click(function(){
        if (!reloj.isRunning()) return;
        var a=$(this).attr("id").split("_");
        var action=a[2];
        var team="";
        t=0;
        team=a[0];
        $.ajax({
            type: "GET",
            url: "/api?method=_putAction",
            data: "tokenEvent="+evento.eventId+"&time="+reloj.seconds+"&team="+team+"&action="+action,
            dataType: "json",
            cache: false,
            success: function(msg){
                refresh();
            }
        });

    });
    $(".btnStart").click(function(){
        if (reloj.isRunning()) {
            reloj.stop();
            $(".time").removeClass("running");
            $(".btn_action").removeClass("active");
            $(this).val("start");
        } else {
            reloj.start();
            $(".time").addClass("running");
            $(".btn_action").addClass("active");
            $(this).val("pause");
        }
    })
    $(".btnEnd").click(function(){
        $.ajax({
            type: "GET",
            url: "/api?method=refreshEvent",
            data: "tokenEvent="+evento.eventId+"&part="+((reloj.part*1)+1)+"&time=0&running=true",
            dataType: "json",
            cache: false,
            success: function(data){
                reloj.stop();
                $(".time").removeClass("running");
                $(".btnStart").val("start");
                var finished=data['finished'];
                var end=data['end'];
                if (end)
                    $(".btnEnd").show();
                else
                    $(".btnEnd").hide();
                var start=data['start'];
                if (start && !finished)
                    $(".btnStart").show();
                else
                    $(".btnStart").hide();

                $(".btn_action").removeClass("active");
                if(!finished){
                    reloj.part++;
                    reloj.seconds=0;
                    reloj.cycle();
                }
            }
        });
    });

    self.setInterval("refresh()",10000);

    if(reloj.seconds>0)
        $(".btnStart").click();
});


